
package com.rabincorp.facepoll.application;

import com.rabincorp.facepoll.dto.PollQuestionDTO;
import java.util.Date;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

/**
 *
 * @author isakrabin
 */
public class PollAppServiceValidator implements Validator{
    
    private final static Log LOGGER = LogFactory.getLog(PollAppServiceValidator.class);

    @Override
    public boolean supports(Class<?> type) {
        return PollQuestionDTO.class.equals(type);
    }

    @Override
    public void validate(Object object, Errors errors) {
        PollQuestionDTO pollQuestionDTO = (PollQuestionDTO) object;
        
        if (StringUtils.isEmpty(pollQuestionDTO.getTitle())) {
            errors.rejectValue("title", "errors.poll.title_empty");
        }
        
        if (StringUtils.isEmpty(pollQuestionDTO.getQuestion())) {
            errors.rejectValue("question","errors.poll.question_empty");
        }
        
        Date currentDate = new Date(System.currentTimeMillis());
        
        if (pollQuestionDTO.getStartDate()!=null) {            
            if (currentDate.after(pollQuestionDTO.getStartDate())) {
                errors.rejectValue("startDate", "errors.poll.start_date_before_today");
            }
            
        }
        
        if (pollQuestionDTO.getEndDate()!=null) {
            if (currentDate.before(pollQuestionDTO.getEndDate())) {
                errors.rejectValue("endDate", "errors.poll.end_date_before_today");
            }
        }
        
        
        if (pollQuestionDTO.getStartDate()!=null && pollQuestionDTO.getEndDate()!=null) {
            if (pollQuestionDTO.getEndDate().before(pollQuestionDTO.getStartDate())) {
                errors.rejectValue("endDate", "errors.poll.end_date_before_start_date");
            }
        }
        
        
        
    }
    
}
